import { ref } from 'vue'
import { useRoute,onBeforeRouteUpdate } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies'
import { router } from '~/router'

export const useTabList = () => {
    const route = useRoute()
const  cookies  = useCookies()

const activeTab = ref(route.path)
const tabList = ref([
  {
    title: '首页',
    path: '/',
  }, 
  // {
  //   title: '商城管理',
  //   path: '/goods/list',
  // }
  
])
// 添加标签导航
function addTab(tab){
  let noTab = tabList.value.findIndex(t=>t.path == tab.path) == -1
  if(noTab){
    tabList.value.push(tab)
  }
  cookies.set('tabList',tabList.value)
}

// 初始化标签导航列表
function initTabList(){
    let tbs = cookies.get("tabList")
    if(tbs){
        tabList.value = tbs
    }
}

initTabList()

onBeforeRouteUpdate((to,from)=>{
  // console.log(
  //   {title:to.meta.title,
  // path:to.path});
  // 更新当前标签(激活状态)
activeTab.value = to.path
  // 添加标签导航
  addTab({title:to.meta.title,path:to.path})
  
})

const changeTab = (t)=>{
  // console.log(t);
  activeTab.value = t
  // // 跳转路由
  router.push(t)
}

const removeTab = (t) => {
    let tabs = tabList.value
    let a = activeTab.value
    if(a == t){
        tabs.forEach((tab,index)=>{
            if(tab.path == t){
                const nextTab = tabs[index+1] || tabs[index-1]
                if(nextTab){
                    a = nextTab.path
                }
            }
        })
    }
    activeTab.value = a
    tabList.value = tabList.value.filter(tab=>tab.path != t)

    cookies.set("tabList",tabList.value)
}

const handleClose=(t)=>{
  if(t=="clearAll"){
    // 切换到首页
    activeTab.value = "/"
    // 清空标签导航
    // tabList.value = []
    // 只剩下首页
    tabList.value = [{title:"首页",path:"/"}]
  } else if(t=="clearOther"){
    // 只剩下首页和当前激活的标签页
    tabList.value = tabList.value.filter(tab=>tab.path == activeTab.value || tab.path == "/")
    // 更新cookie
    cookies.set("tabList",tabList.value)
  }
}

return {
    activeTab,
    tabList,
    changeTab,
    removeTab,
    handleClose
}
}
